<template>
	<view>
		
		<view class="cu-bar bg-white margin-top">
			<view class="action">
				图片上传
			</view>
			<view class="action">
				{{imgList.length}}/1
			</view>
		</view>
		<view class="cu-form-group">
			<view class="grid col-4 grid-square flex-sub">
				<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage"
					:data-url="imgList[index]">
					<image :src="imgList[index]" mode="aspectFill"></image>
					<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
						<text class='cuIcon-close'></text>
					</view>
				</view>
				<view class="solids" @tap="ChooseImage" v-if="imgList.length<4">
					<text class='cuIcon-cameraadd '></text>
				</view>
			</view>
			
			
		</view>
		<view class="padding flex flex-direction">
					<button class="cu-btn bg-gradual-orange margin-tb-sm lg" @tap="UploadImage">上传图片</button>
				</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imgList: [],
			}
		},
		methods: {
			ChooseImage() {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						if (this.imgList.length != 0) {
							this.imgList = this.imgList.concat(res.tempFilePaths)
						} else {
							this.imgList = res.tempFilePaths
						}
					}
				});
			},
			UploadImage(){
				const baseurl=getApp().globalData.BASE_URL;
				const AccountName=JSON.parse(uni.getStorageSync("USERS_KEY")).username;
				const tempFilePaths = this.imgList;
				uni.uploadFile({
					url: baseurl+"/state/UploadImg",
					filePath: tempFilePaths[0],
					name: 'image',
					formData: {
						"stateTitle": AccountName
					},
					header: {
						"Content-Type": "multipart/form-data"
					},
					success: (res) => {
						console.log(res)
						if (res.statusCode === 200) {
							uni.showToast({
								title: "上传成功!",
								success() {
									uni.reLaunch({
										url:"../personal/personal"
									})
										
								}
							});
						} else {
							uni.showToast({
								title: "上传失败!"
							});
						}
						
					},
					fail(e) {
						console.log(e)
					}
				})
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '召唤师',
					content: '确定要删除这段回忆吗？',
					cancelText: '再看看',
					confirmText: '再见',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			
		}
	}
</script>

<style>

</style>
